package sipus.common;

import java.util.ArrayList;
import java.util.Collection;

import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zkoss.zkplus.hibernate.HibernateUtil;

import sipus.database.model.Tbmrole;
import sipus.database.model.Tbmuser;


@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

	@Transactional(readOnly = true)
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {

		Session session = HibernateUtil.getSessionFactory().openSession();
		Tbmuser users = (Tbmuser) session.createCriteria(Tbmuser.class)
				.add(Restrictions.eq("userId", username)).setMaxResults(1)
				.uniqueResult();

		System.out.println("username = " + username + " users = " + users);

		session.disconnect();
		session.close();
		if (users == null) {
			throw new UsernameNotFoundException("user not found");
		}

		String password = null;
		try {
			password = Common.desEncrypter.decrypt(users.getUserPassword()
					.trim());
			System.out.println("password = " + password);
		} catch (Exception e) {
			e.printStackTrace();
		}
		boolean enabled = true;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;

		Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		Tbmrole role = users.getUserRole();
		if (role != null) {
			authorities.add(new GrantedAuthorityImpl("ROLE_USER"));
		}

		if (users != null && users.getRoot() != null && users.getRoot()) {
			authorities.add(new GrantedAuthorityImpl("ROLE_SUPERVISOR"));
		}

		User user = new User(username, password, enabled, accountNonExpired,
				credentialsNonExpired, accountNonLocked, authorities);
		return user;

	}
}